package indi.simple.pms.support.file;

import indi.simple.pms.util.ServletUtil;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


/**
 * @Author: wanglunhui
 * @Date: 2021/7/2 21:43
 * @Description:
 */
@Component
@RequiredArgsConstructor
@Getter
public class LocalFileTemplate {

    private final Config config;

    @SneakyThrows
    public void upload(String fileName, InputStream inputStream){
        Path path= Paths.get(config.getFileUploadPath());
        if(!Files.exists(path)){
            Files.createDirectories(path);
        }

        Files.copy(inputStream,Paths.get(config.getFileUploadPath(),fileName));
    }

    @SneakyThrows
    public InputStream download(String fileName){
        Path path= Paths.get(config.getFileUploadPath());
        if(!Files.exists(path)){
            Files.createDirectories(path);
        }

        InputStream inputStream=Files.newInputStream(Paths.get(config.getFileUploadPath(),fileName));

        return inputStream;
    }

    @SneakyThrows
    public void delete(String fileName){
        Files.delete(Paths.get(config.getFileUploadPath(),fileName));
    }

    @Configuration
    @ConfigurationProperties(prefix = "file")
    @Getter
    @Setter
    public static class Config{

        private String downloadPrefix;
        private String fileUploadPath;
        private String defaultAvatarName;
        private String endpoint;

    }


}
